<?php

namespace App\Controller\AdminApp;

use App\Base\BaseForm;
use App\Repository\AdminUserRepository;
use App\Repository\OrdersRepository;
use App\Repository\OrdersRepository as Repository;
use App\Repository\AdminMenuRepository;
use Doctrine\ODM\MongoDB\DocumentManager;
use App\Base\IRI;
use Symfony\Component\HttpFoundation\Request;
use App\Base\BaseController4Admin;
use App\Entity\Orders as Entity;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/admin/app")
 */
class OrdersAdminApiController extends BaseController4Admin
{
    public $noDelete = [];
    public $entityName = "Orders";
    public $limit = 10;

    /**
     * @Route("/Orders/list",name="AdminAppOrdersGetList")
     */
    public function getList(
        DocumentManager $documentManager,
        AdminUserRepository $adminUserRepository
    )
    {
//        $uid = $this->needToBeAdmin();
        $data = $this->getRequestData();
        $tools = array();
        $page = $data["page"] ?? 1;
        $per_page = $this->limit;
        $rep = $documentManager->getRepository(Entity::class);
        $condition = [];
        if ($where = $data['_where'] ?? []) {

        }
        $where["eq"]["status"] = 1;

        $checkStatus = $data['status']??0;
        if ($checkStatus) {
            if ($checkStatus == 1) {//未到站
                $where["eq"]["checkStatus"] = 0;
            }
            if ($checkStatus == 2) {//未到站
                $where["eq"]["checkStatus"] = 1;
            }
        }

        $condition = createWhere4MongoDB($where);



        if ($search = $data['_search'] ?? []) $condition['$and'] = createSearch4MongoDB($search, ["user.phone", "sn", "payReal"], "or");
        if (!$order = $data["_order"] ?? []) {
            $order = ["id" => "DESC"];
        }
        $list = $rep->findBy($condition, $order, $per_page, $per_page * $page - $per_page);
        $re = [];
        foreach ($list as $row) {
            $orderInfo = $row->getInfo();
            switch ($row->getStatus()) {
                case 0:
                    $status = "未支付";
                    break;
                case 1:
                    $status = "支付完成";
                    break;
                case 2:
                    $status = "申请退款";
                    break;
                case 3:
                    $status = "退款成功";
                    break;
            }
            $re[] = [
                "id" => $row->getId(),
                "user" => $row->getUser()->getName() . "-" . $row->getUser()->getPhone(),
                "sn" => $row->getSn(),
                "payTotal" => $row->getPayTotal(),
                "payReal" => $row->getPayReal(),
                "payCut" => round($row->getPayTotal() - $row->getPayReal(), 2),
                "status" => $row->getCheckStatus() ? "已完成" : "未到站",
                "createAt" => $row->getCreateAt()->format($this->YYMMDDHHIISS),
                "orderInfo" => $orderInfo,
                "info" => $orderInfo["oil"] . $orderInfo["gun"],
            ];
        }
        $list= $this->normalize($list);
        foreach ($list as &$row) {
            $row["checkAdmin"] =$adminUserRepository->find($row["checkUser"]);
        }
        $qb = $documentManager->createQueryBuilder(Entity::class);
        $total = $qb->setQueryArray($condition)->count()->getQuery()->execute();
        /*URL配置*/
//        $urls = array(
//            "toolUrl" => $this->generateUrl("OrdersTools"),
//            "addUrl" => $this->generateUrl("OrdersPreAdd"),
//        );
//        $this->clearGroups();
//        $config = getEntityAnnotationData(Entity::class);
        $data = array(
//            'en'     => "Orders",
//            'title'     => "列表",
//            'header'     => ["user","sn","payTotal","payReal","info","createAt"],
//            "tools"     => $tools,
//            'urls'      => $urls,
//            "config"    => $config,
            'lists' => $list,
            "page" => ['total' => $total, "limit" => $per_page, "page" => $page * 1],
        );
        return $this->json_out(1, 'OK', $data);
    }


    /**
     * @Route("/Orders/check",name="AdminAppOrdersCheck")
     */
    public function AdminAppOrdersCheck(
        OrdersRepository $repository,
        AdminUserRepository $adminUserRepository
    )
    {
        $uid = $this->needToBeAdmin();
        $req = $this->getRequestData();
        $code = $req["code"] ?? "";
        if(!$code = $this->getParamRequired("code")){return $this->json_out(0,"扫码错误");}
        if(!$view = $this->getParamRequired("view")){$view = 0;}
        $order = $repository->findOneBy(array('sn' => "$code"));
        if (!$order) {
            return $this->json_out(0, "信息未找到");
        }
        $admin = $adminUserRepository->find($uid);
        if ($view == 1) {
            //仅获取订单详情
            return $this->json_out(1, "信息获取成功",$order);
        }
        $order->setCheckStatus(1)
            ->setCheckAt(new \DateTime())
            ->setCheckUser($admin->getId());
        $this->myEm()->persist($order);
        $this->myEm()->flush();
        return $this->json_out(1, "核销成功");
    }

    /**
     * @Route("/Orders/calc",name="AdminAppOrdersCalc")
     */
    public function AdminAppOrdersCalc(
        DocumentManager $documentManager,
        OrdersRepository $repository,
        AdminUserRepository $adminUserRepository
    )
    {
        $rep = $documentManager->getRepository(Entity::class);
        $condition = [];
        if ($where = $data['_where'] ?? []) {

        }
        $where["eq"]["status"] = 1;
        $date = new \DateTime();
        $date->setTimestamp(getDayStart());
        $where["gt"]["createAt"] = $date->format($this->YYMMDDHHIISS);

//        $condition = createWhere4MongoDB($where);
        $condition["createAt"]['$gt']=$date;
        $condition["status"]=1;

        $list = $rep->findBy($condition);
        $num = count($list);
        $sum = 0;
        foreach ($list as $row) {
            $sum += $row->getPayReal();
        }
        $data["num"]= $num;
        $data["sum"] = round($sum,2);
        return $this->json_out(1,"OK",$data);
    }
}
